<template>
  <div class="customer-manage">
    <div class="page-header">
      <i class="el-icon-user"></i>
      <span>客户管理</span>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入客户姓名/手机号进行搜索"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
      </el-input>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="handleSearch">查询</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="!selectedRows.length">删除</el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="customerName" label="客户姓名" min-width="120" align="center"></el-table-column>
      <el-table-column prop="phoneNumber" label="手机号" min-width="120" align="center"></el-table-column>
      <el-table-column label="客户类型" width="100" align="center">
        <template slot-scope="scope">
          <el-tag size="small" type="info">
            {{ scope.row.customerType === 1 ? '个人用户' : '企业用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="idCardNumber" label="身份证号" min-width="180" align="center"></el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" min-width="120" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            type="text" 
            size="small" 
            :style="{ color: scope.row.status === 2 ? '#409EFF' : '#F56C6C' }"
            @click="handleDisable(scope.row)"
          >
            {{ scope.row.status === 2 ? '启用' : '禁用' }}
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        
        <el-form-item label="客户类型" prop="customerType">
          <el-radio-group v-model="formData.customerType">
            <el-radio :label="1">个人用户</el-radio>
            <el-radio :label="2">企业用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="formData.idCardNumber" placeholder="请输入身份证号"></el-input>
        </el-form-item>

        <el-form-item label="账户类型" prop="accountType">
          <el-select v-model="formData.accountType" placeholder="请选择账户类型">
            <el-option label="储值账户" value="储值账户"></el-option>
            <el-option label="记账账户" value="记账账户"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input
            type="textarea"
            :rows="3"
            v-model="formData.remarks"
            placeholder="请输入备注信息">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CustomerManage',
  data() {
    // 身份证号验证规则
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的身份证号'));
        }
      }
    };

    return {
      searchQuery: '',
      loading: false,
      submitLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '新增客户',
      formData: {
        id: null,
        customerName: '',
        phoneNumber: '',
        customerType: 1,
        idCardNumber: '',
        accountType: '储值账户',
        status: 1,
        remarks: ''
      },
      formRules: {
        customerName: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        customerType: [
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ],
        idCardNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        accountType: [
          { required: true, message: '请选择账户类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    loadData() {
      this.loading = true;
      this.$axios.get('/api/customer/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery ? this.searchQuery.trim() : null
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          this.tableData = response.data.data;
          this.total = response.data.total || this.tableData.length;
        } else {
          this.$message.error(response.data.msg || '获取客户列表失败');
        }
      })
      .catch(error => {
        console.error('获取客户列表失败:', error);
        this.$message.error('获取客户列表失败，请稍后重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    handleSearch() {
      this.currentPage = 1;
      this.loadData();
    },

    handleAdd() {
      this.dialogTitle = '新增客户';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
      });
    },

    handleEdit(row) {
      this.dialogTitle = '编辑客户';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.formData = { ...row };
      });
    },

    handleDelete(row) {
      this.$confirm('确认删除该客户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/api/customer/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.loadData();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      }).catch(() => {});
    },

    handleBatchDelete() {
      if (!this.selectedRows.length) return;
      
      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deletePromises = this.selectedRows.map(row => 
          this.$axios.delete(`/api/customer/${row.id}`)
        );

        Promise.all(deletePromises)
          .then(() => {
            this.$message.success('批量删除成功');
            this.loadData();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败，请稍后重试');
          });
      }).catch(() => {});
    },

    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const isEdit = this.formData.id !== null;
          const api = isEdit ? '/api/customer/update' : '/api/customer/add';
          
          this.submitLoading = true;
          this.$axios.post(api, this.formData)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(isEdit ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                this.loadData();
              } else {
                this.$message.error(response.data.msg || (isEdit ? '修改失败' : '添加失败'));
              }
            })
            .catch(error => {
              console.error(isEdit ? '修改客户失败:' : '添加客户失败:', error);
              this.$message.error(isEdit ? '修改失败，请稍后重试' : '添加失败，请稍后重试');
            })
            .finally(() => {
              this.submitLoading = false;
            });
        }
      });
    },

    handleDialogClose() {
      this.$refs.formRef.resetFields();
      this.formData = {
        id: null,
        customerName: '',
        phoneNumber: '',
        customerType: 1,
        idCardNumber: '',
        accountType: '储值账户',
        status: 1,
        remarks: ''
      };
      this.dialogVisible = false;
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPage = 1;
      this.loadData();
    },

    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.loadData();
    },

    handleView(row) {
      // 查看功能待实现
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 1:
          return '正常';
        case 2:
          return '已禁用';
        default:
          return '未知';
      }
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'success';
        case 2:
          return 'danger';
        default:
          return 'info';
      }
    },

    // 禁用/启用客户
    handleDisable(row) {
      const action = row.status === 2 ? '启用' : '禁用';
      this.$confirm(`确认${action}该客户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updateData = {
          ...row,
          status: row.status === 2 ? 1 : 2  // 在 1 和 2 之间切换
        };
        
        this.$axios.post('/api/customer/update', updateData)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success(`${action}成功`);
              this.loadData(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || `${action}失败`);
            }
          })
          .catch(error => {
            console.error(`${action}客户失败:`, error);
            this.$message.error(`${action}失败，请稍后重试`);
          });
      }).catch(() => {});
    }
  },
  created() {
    this.loadData();
  }
}
</script>

<style scoped>
.customer-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  font-size: 24px;
  margin-right: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

:deep(.el-button--text + .el-button--text) {
  margin-left: 0;
}

:deep(.el-tag) {
  text-transform: uppercase;
}
</style>
